package com.cadre.common.utils.oldutil;

import cn.hutool.core.util.RandomUtil;
import com.cadre.common.exception.CadreException;
import com.cadre.common.utils.common.DateUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark;
import org.springframework.core.io.ClassPathResource;
import org.w3c.dom.Node;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

/* loaded from: Renmb4word.class */
public class Renmb4word {
    public static final String RUN_NODE_NAME = "w:r";
    public static final String TEXT_NODE_NAME = "w:t";
    public static final String BOOKMARK_START_TAG = "bookmarkStart";
    public static final String BOOKMARK_END_TAG = "bookmarkEnd";
    public static final String BOOKMARK_ID_ATTR_NAME = "w:id";
    public static final String STYLE_NODE_NAME = "w:rPr";
    private static final String SEPARATION = "/";
    private List<Map<String, Object>> listData;
    private Map<String, Object> data;
    private String path;
    XWPFDocument document;
    XWPFTableCell currentCell;
    String templatePath;
    private static final String fileName = "干部任免审批表";

    public Renmb4word(List<Map<String, Object>> map, String templatePath) {
        this.templatePath = templatePath;
        this.listData = map;
        String relativePath = Renmb4word.class.getClassLoader().getResource("tempfile/temp.txt").getPath();
        String finpath = relativePath.substring(0, relativePath.lastIndexOf(SEPARATION));
        this.path = finpath + SEPARATION + DateUtils.format(new Date()) + SEPARATION + RandomUtil.getRandom() + SEPARATION;
    }

    public void setTempValue(HttpServletResponse response) {
        XWPFDocument doc = null;
        File folder = new File(this.path);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        try {
            try {
                File file = new File(this.path + fileName + ".docx");
                for (int i = 0; i < this.listData.size(); i++) {
                    this.data = this.listData.get(i);
                    this.document = new XWPFDocument(new ClassPathResource(this.templatePath).getInputStream());
                    replaceTable();
                    replaceParagraph();
                    if (i == 0) {
                        doc = this.document;
                    } else {
                        RenmbReportHelper.insertNextPageChar(doc);
                        RenmbReportHelper.appendBody(doc, this.document);
                    }
                }
                OutputStream out = new FileOutputStream(file);
                doc.write(out);
                out.flush();
                out.close();
                MergePDF.wordToPdf(file.getAbsolutePath(), file.getParent() + SEPARATION + fileName + ".pdf");
                WordUtils.showPdf(response, this.path + fileName + ".pdf");
                System.out.println("需要删除的文件>>>>>>>>>>>>>>>>>" + this.path);
                WordUtils.deleteDir(this.path);
            } catch (Exception e) {
                e.printStackTrace();
                throw new CadreException(ResultEnum.OFFICE_ERROR);
            }
        } catch (Throwable th) {
            System.out.println("需要删除的文件>>>>>>>>>>>>>>>>>" + this.path);
            WordUtils.deleteDir(this.path);
            throw th;
        }
    }

    public void replaceParagraph() {
        for (XWPFParagraph paragraph : this.document.getParagraphs()) {
            for (CTBookmark bookmark : paragraph.getCTP().getBookmarkStartList()) {
                CellHandlerFactory.getHandler(bookmark.getName()).setValue(paragraph, this.data);
            }
        }
    }

    public void replaceTable() {
        for (XWPFTable table : this.document.getTables()) {
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    this.currentCell = cell;
                    setCellValue();
                }
            }
        }
    }

    private void setCellValue() {
        List<XWPFParagraph> paragraphList = this.currentCell.getParagraphs();
        for (int i = 0; i < paragraphList.size(); i++) {
            XWPFParagraph paragraph = paragraphList.get(i);
            for (CTBookmark bookmark : paragraph.getCTP().getBookmarkStartList()) {
                CellHandlerFactory.getHandler(bookmark.getName()).setValue(paragraph, this.data);
            }
        }
    }

    private void setYearMd(XWPFParagraph paragraph, CTBookmark bookmark) {
        XWPFRun run = paragraph.createRun();
        if (this.data.get(bookmark.getName()) != null) {
            String value = this.data.get(bookmark.getName()).toString();
            run.setFontSize(14);
            run.setText(value);
        }
    }

    private void insertAfterBookmark(XWPFParagraph paragraph, XWPFRun run, CTBookmark bookmark) {
        Node styleNode = null;
        int bookmarkEndID = -1;
        int bookmarkStartID = bookmark.getId().intValue();
        Node nextNode = bookmark.getDomNode();
        while (bookmarkStartID != bookmarkEndID) {
            nextNode = nextNode.getNextSibling();
            if (nextNode.getNodeName().contains(BOOKMARK_END_TAG)) {
                try {
                    bookmarkEndID = Integer.parseInt(nextNode.getAttributes().getNamedItem(BOOKMARK_ID_ATTR_NAME).getNodeValue());
                } catch (NumberFormatException e) {
                    bookmarkEndID = bookmarkStartID;
                }
            } else if (nextNode.getNodeName().equals(RUN_NODE_NAME)) {
                styleNode = getStyleNode(nextNode);
            }
        }
        Node insertBeforeNode = nextNode.getNextSibling();
        if (styleNode != null) {
            run.getCTR().getDomNode().insertBefore(styleNode.cloneNode(true), run.getCTR().getDomNode().getFirstChild());
        }
        if (insertBeforeNode != null) {
            paragraph.getCTP().getDomNode().insertBefore(run.getCTR().getDomNode(), insertBeforeNode);
        }
    }

    private Node getStyleNode(Node parentNode) {
        Node styleNode = null;
        if (parentNode != null && parentNode.getNodeName().equalsIgnoreCase(RUN_NODE_NAME) && parentNode.hasChildNodes()) {
            Node childNode = parentNode.getFirstChild();
            if (!childNode.getNodeName().equals(STYLE_NODE_NAME)) {
                while (true) {
                    Node nextSibling = childNode.getNextSibling();
                    childNode = nextSibling;
                    if (nextSibling == null) {
                        break;
                    } else if (childNode.getNodeName().equals(STYLE_NODE_NAME)) {
                        styleNode = childNode;
                        childNode = null;
                    }
                }
            } else {
                styleNode = childNode;
            }
        }
        return styleNode;
    }
}
